package com.ossjk.oa.config.wxlogin;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Configuration
public class WxLoginConfig {
	@Value("${wx.appid}")
	private String appid;
	@Value("${wx.secret}")
	private String secret;

	/**
	 * 获取AccessToken
	 * 
	 * @param code
	 * @return
	 * @throws Exception
	 */
	public WxLoginVo getWxAccessToken(String code) throws Exception {
		WxLoginVo wxLoginVo = null;
		OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
		Request request = new Request.Builder().url("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code").build();
		Response response = okHttpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			String str = response.body().string();
			JSONObject onResponse = JSONObject.parseObject(str);
			wxLoginVo = new WxLoginVo();
			wxLoginVo.setAccessToke(onResponse.getString("access_token"));
			wxLoginVo.setOpenid(onResponse.getString("openid"));
		}
		return wxLoginVo;
	}

	/**
	 * 获取Uid
	 * 
	 * @param code
	 * @return
	 * @throws Exception
	 */
	public WxLoginVo getUid(WxLoginVo wxLoginVo) throws Exception {
		OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
		Request request = new Request.Builder().url("https://api.weixin.qq.com/sns/userinfo?access_token=" + wxLoginVo.getAccessToke() + "&openid=" + wxLoginVo.getOpenid()).build();
		Response response = okHttpClient.newCall(request).execute();
		JSONObject onResponse = JSONObject.parseObject(response.body().string());
		wxLoginVo.setUnionid(onResponse.getString("unionid"));
		return wxLoginVo;
	}

	/**
	 * 微信登陆
	 * 
	 * @param code
	 * @return
	 * @throws Exception
	 */
	public WxLoginVo wxLogin(String code) throws Exception {
		WxLoginVo wxLoginVo = getWxAccessToken(code);
		return getUid(wxLoginVo);
	}

}
